﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Common
{
    /// <summary>
    /// 程序集帮助类
    /// .NetFramework使用
    /// </summary>
    public static class AssemblyUtility
    {
        private static IEnumerable<Assembly> allReferencedAssemblies;

        /// <summary>
        /// 所有引用的程序集
        /// </summary>
        public static IEnumerable<Assembly> AllReferencedAssemblies
        {
            get
            {
                if (allReferencedAssemblies == null || allReferencedAssemblies.Count() == 0)
                {
                    allReferencedAssemblies = GetAllReferencedAssemblies();
                }
                return allReferencedAssemblies;
            }
        }

        /// <summary>
        /// 获取所有引用的程序集
        /// </summary>
        /// <returns></returns>
        public static List<Assembly> GetAllReferencedAssemblies()
        {
            var result = new List<Assembly>();

            //当前加载的程序集
            var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.FullName.StartsWith("System") && !a.FullName.StartsWith("Microsoft")).ToArray();
            result.AddRange(loadedAssemblies);
            foreach (var item in loadedAssemblies)
            {
                GetReferanceAssemblies(item, result);
            }

            return result;
        }

        /// <summary>
        /// 动态调用程序集方法
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="classFullName"></param>
        /// <param name="methodName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string CallAssembly(string assemblyName, string classFullName, string methodName, object[] parameters)
        {
            string result = "";

            //加载目标程序集
            Assembly assembly = Assembly.LoadFrom($"{AppDomain.CurrentDomain.BaseDirectory}/bin/{assemblyName}.dll");
            //获取目标类
            Type classType = assembly.GetType(classFullName);
            //获取目标方法
            MethodInfo method = classType.GetMethod(methodName);
            object methodResult = null;
            if (method.IsStatic)
            {
                methodResult = method.Invoke(classType, parameters);
            }
            else
            {
                object classTypeInstance = Activator.CreateInstance(classType);
                methodResult = method.Invoke(classTypeInstance, parameters);
            }
            if (methodResult != null)
            {
                if (methodResult is string)
                {
                    result = methodResult.ToString();
                }
                else
                {
                    var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                    result = JsonConvert.SerializeObject(methodResult, timeConverter);
                }
            }

            return result;
        }

        #region 私有方法
        /// <summary>
        /// 获取引用的程序集
        /// </summary>
        /// <param name="assembly"></param>
        /// <returns></returns>
        private static void GetReferanceAssemblies(Assembly assembly, List<Assembly> result)
        {
            foreach (var item in assembly.GetReferencedAssemblies().Where(a => !a.FullName.StartsWith("System") && !a.FullName.StartsWith("Microsoft")))
            {
                try
                {
                    Assembly referencedAssembly = Assembly.Load(item);
                    if (!result.Contains(referencedAssembly))
                    {
                        result.Add(referencedAssembly);
                        GetReferanceAssemblies(referencedAssembly, result);
                    }
                }
                catch (Exception ex)
                {
                    //部分程序集加载不了，跳过。
                    Console.WriteLine($"报错：{ex}");
                }
            }
        }
        #endregion
    }
}
